// 延时
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// 返回顶部
const fnBackTop = async () => {
  const curTop = document.documentElement.scrollTop;
  // console.log('curTop', curTop);
  if (curTop > 4) {
    await sleep(17);
    document.documentElement.scrollTop = curTop - curTop / 4;
    fnBackTop();
  }
};

const titleData = {
  'zbp_name': '',
  'zbp_subname': '',
  'lstTpl': '',
};

export default {
  _log: (...args) => console.log('[debug-log]', ...args),
  _warn: (...args) => console.warn('[debug-warn]', ...args),
  _error: (...args) => console.error('[debug-error]', ...args),
  // backTop: () => (fnBackTop()),
  backTop: fnBackTop,
  htmlEscape: (text) => {
    return text.replace(/&(lt|gt|amp|quote|quot);/g, (match) => {
      switch (match) {
        case '&lt;':
          return '<';
        case '&gt;':
          return '>';
        case '&amp;':
          return '&';
        case '&quote;':
          return '"';
        case '&quot;':
          return '"';
        default:
      }
      return match;
    });
  },
  removeHTML: (html) => {
    return html.replace(/<[^<>]+>/g, '');
  },
  parseTags: (Tag, TagsName) => {
    const result = [];
    const matchTag = Tag.match(/(?<id>\d+)/g);
    const arrNames = TagsName.split(',');
    matchTag.forEach((ID, i) => {
      result.push({
        ID,
        Name: arrNames[i],
      });

    });
    return result;
  },
  setTitle: (type = '', args = {}) => {
    let title = '';
    let curTpl = '';
    switch (type) {
      case 'System':
        titleData.zbp_name = args.name;
        titleData.zbp_subname = args.subname;
        curTpl = '{{zbp_name}} - {{zbp_subname}}';
        break;
      case 'Index':
        curTpl = '{{zbp_name}} - {{zbp_subname}}';
        break;
      case 'Post':
        curTpl = `${args.Title} - {{zbp_name}} - {{zbp_subname}}`;
        break;
      case 'Load':
      default:
        titleData.lstTpl = 'Loading...';
        break;
    }
    if (titleData.zbp_name && titleData.zbp_subname && curTpl) {
      titleData.lstTpl = curTpl;
    }
    if (titleData.lstTpl) {
      title = titleData.lstTpl.replace(/{{(.*?)}}/g, (match, p1) => {
        return titleData[p1] || '';
      });
    }
    // if (args.msg) {
    //   title = `${title} - ${args.msg}`;
    //   if (args.params) {
    //     console.log(args.params);
    //   }
    // }
    // console.log(type, title);
    document.title = title;
  }
};
